package com.knife.tools;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import tools.ConvertDocument;

import com.knife.news.logic.NewsService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.impl.NewsServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.object.News;
import com.knife.news.object.Site;
import com.knife.util.CommUtil;
import com.knife.web.Globals;

public class DocImport extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private NewsService newsDAO = new NewsServiceImpl();
	private SiteService siteDAO = new SiteServiceImpl();
	private String basicName = "";
	private String author = "";
	private String sitePath = "";
	private String filext = "";

	@SuppressWarnings("rawtypes")
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		Boolean ret = false;
		res.setContentType("text/html; charset=UTF-8");
		req.setCharacterEncoding("UTF-8");
		// 如果有附件,先上传附件
		System.out.println("发现资料，开始执行上传");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		String filename = "";
		String tmpfilePath = Globals.APP_BASE_DIR + "upload" + File.separator;
		factory.setRepository(new File(tmpfilePath));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(5 * 1024 * 1024 * 1024);
		try {
			String sid = CommUtil.null2String(req.getParameter("sid"));
			Site site = new Site();
			if(sid.length()>0){
				site = siteDAO.getSiteById(sid);
			}else{
				site = siteDAO.getSite();
			}
			String tid = CommUtil.null2String(req.getParameter("tid"));
			List fileItems = upload.parseRequest(req);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					filename = item.getName();
					filext = FilenameUtils.getExtension(filename);
					basicName = filename
							.substring(0, filename.lastIndexOf("."));
					if (filext.trim().length() <= 0) {
						if (filename.indexOf(".") > 0) {
							filext = filename.substring(
									filename.lastIndexOf(".") + 1,
									filename.length());
						}
					}
					UUID uid = UUID.randomUUID();
					String basicname = uid.toString();
					String newfilename = basicname + "." + filext;
					String htmlfilename = basicname + ".html";
					System.out.println("文章标题为:" + basicName + ",识别出文件后缀为:"
							+ filext);
					String subdir = "";
					if (filext.equals("jpg") || filext.equals("jpeg")
							|| filext.equals("gif") || filext.equals("bmp")
							|| filext.equals("png")) {
						subdir = "images";
					} else if (filext.equals("doc") || filext.equals("docx")
							|| filext.equals("ppt") || filext.equals("pptx")
							|| filext.equals("xls") || filext.equals("xlsx")
							|| filext.equals("pdf")) {
						subdir = "office";
					} else if (filext.equals("mpg") || filext.equals("wmv")
							|| filext.equals("3gp") || filext.equals("mov")
							|| filext.equals("mp4") || filext.equals("asf")
							|| filext.equals("asx") || filext.equals("flv")) {
						subdir = "videos";
					} else if (filext.equals("mp3") || filext.equals("wma")) {
						subdir = "audios";
					} else {
						subdir = "others";
					}
					String filePath = Globals.APP_BASE_DIR + "html" + File.separator
							+ site.getPub_dir() + File.separator + "upload"
							+ File.separator + subdir + File.separator
							+ Calendar.getInstance().get(Calendar.YEAR)
							+ File.separator
							+ (Calendar.getInstance().get(Calendar.MONTH)+1)
							+ File.separator;
					String pubPath = Globals.APP_BASE_DIR + "wwwroot" + File.separator
							+ site.getPub_dir() + File.separator + "upload"
							+ File.separator + subdir + File.separator
							+ Calendar.getInstance().get(Calendar.YEAR)
							+ File.separator
							+ (Calendar.getInstance().get(Calendar.MONTH)+1)
							+ File.separator;
					sitePath="/html/"+site.getPub_dir()+"/upload/"+ subdir + "/"
						+ Calendar.getInstance().get(Calendar.YEAR)
						+ "/"
						+ (Calendar.getInstance().get(Calendar.MONTH)+1)
						+ "/";
					long size = item.getSize();
					if ((filename == null || filename.equals("")) && size == 0) {
						continue;
					}
					try {
						File realfile = new File(filePath + newfilename);
						// 保存上传的文件到指定的目录
						if (!(realfile.getParentFile().exists())) {
							realfile.getParentFile().mkdirs();
						}
						if (realfile.exists()) {
							newfilename = newfilename.substring(0,
									newfilename.lastIndexOf("."))
									+ "_1." + filext;
							htmlfilename = newfilename.substring(0,
									newfilename.lastIndexOf("."))
									+ "_1.html";
							realfile = new File(filePath + newfilename);
						}
						item.write(realfile);
						
						// 上传完毕后开始转换
						if (subdir.equals("office")) {
							System.out.println("识别出文档文件，开始转换：" + filePath
									+ newfilename);
							if(realfile.exists()){
								ConvertDocument.convertToHTML(filePath + newfilename);
							}else{
								System.out.println("未找到文档文件");
							}
							// 读取html内容,并写入数据库
							File input = new File(filePath + htmlfilename);
							if (input.exists()) {
								String encode=CheckCharset.checkFileEncoding(input);
								Document doc = Jsoup.parse(input,encode);
								Element head = doc.head();
								Elements metas = head.select("meta");
								for (Element meta : metas) {
								    if ("AUTHOR".equalsIgnoreCase(meta.attr("name"))){
								        //System.out.println(meta.attr("content"));
								        author = meta.attr("content");
								    }
								}
								String content = doc.html();
								content = content.replaceAll("(?i)(<img[^>]*?src=\")(.*)(\")", "$1"+sitePath+"$2$3");
								//content = Jsoup.clean(doc.html(),Whitelist.relaxed());
								//替换正文中的图片链接
								//content = content.replaceAll("(<[img|IMG][^>]*?[src|SRC]=\")(.*)(\")", "$1"+sitePath+"$2$3");
								News anews = new News();
								anews.setTitle(basicName);
								anews.setType(tid);
								anews.setAuthor(author);
								anews.setDate(new Date());
								anews.setCommend("0");
								anews.setDisplay(0);
								anews.setContent(content);
								if(newsDAO.addNews(anews).length()>0){
									ret=true;
								}
								System.out.println("导入文章:" + basicName);
								input.delete();
							}
							// 写入数据后,删除临时html
							File tmpHTML = new File(filePath + htmlfilename);
							if (tmpHTML.exists()) {
								tmpHTML.delete();
							}
						}
						
						if(site.getHtml()==1){
							CopyDirectory.copyFile(realfile, new File(pubPath+newfilename));
							if(site.getBig5()==1){
								String big5Path = (filePath + newfilename).replace(site.getPub_dir() + File.separator + "upload", site.getPub_dir() + File.separator + "big5"+File.separator+"upload");
								CopyDirectory.copyFile(realfile, new File(big5Path));
								String big5PubPath = (pubPath+newfilename).replace(site.getPub_dir() + File.separator + "upload", site.getPub_dir() + File.separator + "big5"+File.separator+"upload");
								CopyDirectory.copyFile(realfile, new File(big5PubPath));
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		System.out.println(ret);
		//out.print(ret);
	}
}